#include <jni.h>
#include <stdlib.h>

#include "haptimap_internal.h" /* needed to access hm->platform_init_privdata */
#include "haptimap_android_jni.h"
#include "common.h"

jint Java_org_haptimap_HaptiMap_Initialise(JNIEnv *env, jobject wrapper)
{
    hm_t *hm;
	 
    struct hm_android_data *adata = calloc(1, sizeof(struct hm_android_data));

    /* Retrieve copy of Android application context and store where toolkit
     * internal functions may access it if necessary. */
    adata->context = (*env)->GetObjectField(env, wrapper, 
                                            (*env)->GetFieldID(env, (*env)->GetObjectClass(env, wrapper),
                                                               "context", "Landroid/content/Context;"));
    adata->context = (*env)->NewGlobalRef(env, adata->context);

    if( !(hm = hm_init_with_privdata(adata)))
    {
        (*env)->DeleteGlobalRef(env, adata->context);
        free(adata);
        return HM_FAILURE;
    }

    /* Store the hm_t pointer in the application context */
	 SET_HM(wrapper, hm);

    return HM_SUCCESS;
}

jint Java_org_haptimap_HaptiMap_Uninitialise(JNIEnv *env, jobject wrapper)
{
    hm_t *hm = GET_HM(wrapper);
    struct hm_android_data *adata = hm->platform_init_privdata;

    if(!hm)
        return HM_FAILURE;

    if(hm_destroy(hm) != HM_SUCCESS)
        return HM_FAILURE;

    (*env)->DeleteGlobalRef(env, adata->context);
    free(adata);
    SET_HM(wrapper, NULL);
    return HM_SUCCESS;
}
